package net.osweb.core.fw.service.impl;

import java.io.Serializable;

import net.osweb.core.fw.dao.GenericDao;
import net.osweb.core.fw.dto.BaseDto;
import net.osweb.core.fw.exception.CacheException;
import net.osweb.core.fw.exception.ServiceException;
import net.osweb.core.fw.service.BaseManager;
import net.osweb.core.fw.service.PojoCacheOperator;

/**
 * liwu E-mail:
 * 
 * @version 创建时间：Jun 2, 2011 4:06:50 PM 类说明
 */


public abstract class BaseManagerAbstract<T, PK extends Serializable>
		extends GenericManagerImpl<T, PK> implements BaseManager<T, PK> {
	public BaseManagerAbstract(){
		super();
	}
	public BaseManagerAbstract(GenericDao<T, PK> genericDao){
		super( genericDao );
	}
	
	/**
	 * 模板方法模式，根据id获取对象必须使用该接口方法。 如果对象存在于缓存，直接返回。 如果没有。从数据库读取，转换成dto,并缓存dto对象。
	 * 
	 * @param dto
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public BaseDto get(BaseDto dto) {
		if (null == dto)
			return null;
		else {
			BaseDto newDto = null;
			try {
				newDto = PojoCacheOperator.getFromCache(dto);
			} catch (CacheException ex) {
				this.log.error("cache error:" + ex);
			}

			try {
				if (null == newDto) {
					T model = this.get((PK) dto.getId());
					if (null != model) {
						newDto = trans2Dto(model);
						if (newDto != null) {
							PojoCacheOperator.add2Cache(newDto);
						}
					}
				}
			} catch (Exception ex) {
				this.log.error(ex);
				throw new ServiceException(ex);
			}
			return newDto;
		}
	}

	/**
	 * 保存。持久化model，并缓存dto;
	 * 
	 * @param dto
	 */
	public void saveAndCache(BaseDto dto) {
		try {
			T model = trans2Model(dto);
			this.save(model);
			PojoCacheOperator.add2Cache(dto);
		} catch (Exception ex) {
			this.log.error(ex);
			throw new ServiceException(ex);
		}
	}

	/**
	 * 更新。持久化model，并缓存dto;
	 * 
	 * @param dto
	 */
	public void updateAndCache(BaseDto dto) {
		try {
			T model = trans2Model(dto);
			this.save(model);
			PojoCacheOperator.add2Cache(dto);
		} catch (Exception ex) {
			this.log.error(ex);
			throw new ServiceException(ex);
		}
	}

	@SuppressWarnings("unchecked")
	public void remove(BaseDto dto) {
		try {
			this.remove((PK) dto.getId());
			PojoCacheOperator.removeFromCache(dto);
		} catch (Exception ex) {
			this.log.error(ex);
			throw new ServiceException(ex);
		}
	}
	
	public void removeFromCache(BaseDto dto) {
		try {
			PojoCacheOperator.removeFromCache(dto);
		} catch (Exception ex) {
			this.log.error(ex);
			throw new ServiceException(ex);
		}
	}
	
	public void replaceCache(BaseDto dto) {
		try {
			PojoCacheOperator.replaceCache(dto);
		} catch (CacheException e) {
			log.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 抽象方法，由子类实现; model，dto转换
	 * 
	 * @param dto
	 */
	public abstract BaseDto trans2Dto(T t);

	public abstract T trans2Model(BaseDto dto);
}
